package com.me.test.config;

        
import com.rabbitmq.client.AMQP;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
@Slf4j
public class RabbitProducer {

  @Autowired
  RabbitTemplate rabbitTemplate;

   /**
   * 1 设置 confirm 回调，消息发送到 exchange 时回调
   * 2 设置 return callback ,当路由规则无法匹配到消息队列时，回调
   * correlationData：消息发送时，传递的参数，里边只有一个id属性，标识消息用
   */
  @PostConstruct
  public void enableConfirmCallback(){
    // #1
    /**
     * 连接不上 exchange或exchange不存在时回调
     */
    rabbitTemplate.setConfirmCallback((correlationData,ack,cause)->{
      if (!ack) {
        log.error("消息发送失败");
        // TODO 记录日志，发送通知等逻辑
       }
     });

    // #2
    /**
     * 消息投递到队列失败时，才会回调该方法
     * message:发送的消息
     * exchange:消息发往的交换器的名称
     * routingKey:消息携带的路由关键字信息
     */
    rabbitTemplate.setReturnCallback((message,replyCode,replyText,exchange,routingKey) ->{
      log.error("消息路由失败");
      // TODO 路由失败后续处理逻辑
     });
   }

   public void send(String msg){
        String exchangeName = "my-exchange";
        // String routingKey  = "aaa.xxx";
        String routingKey  = "rabbit.test";
        rabbitTemplate.convertAndSend(exchangeName, routingKey, msg);
   }
}
